package cn.geminis.workflow.service.utils;

import org.flowable.bpmn.model.*;
import org.flowable.task.api.history.HistoricTaskInstance;

import java.util.List;
import java.util.Objects;

/**
 * @author puddi
 */
public class WorkflowUtils {

//    public static List<SequenceFlow> getElementIncomingFlows(FlowElement source) {
//        List<SequenceFlow> sequenceFlows = null;
//        if (source instanceof Task) {
//            sequenceFlows = ((Task) source).getIncomingFlows();
//        } else if (source instanceof Gateway) {
//            sequenceFlows = ((Gateway) source).getIncomingFlows();
//        } else if (source instanceof SubProcess) {
//            sequenceFlows = ((SubProcess) source).getIncomingFlows();
//        } else if (source instanceof StartEvent) {
//            sequenceFlows = ((StartEvent) source).getIncomingFlows();
//        } else if (source instanceof EndEvent) {
//            sequenceFlows = ((EndEvent) source).getIncomingFlows();
//        }
//        return sequenceFlows;
//    }

    public static void taskInstancesBackwardBetween2Tasks(Task taskFrom, String taskToKey, List<HistoricTaskInstance> instances, List<HistoricTaskInstance> result) {
        var flows = taskFrom.getIncomingFlows();
        flows.forEach(flow -> {
            var previousTask = flow.getSourceFlowElement();
            if (previousTask.getId().equals(taskToKey)) {
                return;
            }
            var matchInstance = instances.stream()
                    .filter(instance -> instance.getTaskDefinitionKey().equals(previousTask.getId())).findAny();
            if (previousTask instanceof Task
                    && matchInstance.isPresent()
                    && !result.contains(matchInstance.get())) {
                result.add(matchInstance.get());
                taskInstancesBackwardBetween2Tasks((Task) previousTask, taskToKey, instances, result);
            }
        });
    }

}
